import dayjs from 'dayjs'

import { stopServiceApi } from '@/api/pcs/pcsCompanionOrder'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { formatDate } from '@/utils/displayHelper'
import { PCS_COMPANION_PERIOD_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import DatePickerWithSelect from '../DatePickerWithSelect'

const StopModal = ({ detailData }) => {
  const [form] = AekForm.useForm()

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      label: '结束时间',
      field: 'endTime',
      formItemProps: {
        rules: [
          { required: true, message: ' ' },
          {
            validator: async (rule, value) => {
              if (!value || !value?.datePicker || !value?.select) {
                return Promise.reject('请选择结束时间')
              }
              Promise.resolve()
            },
          },
        ],
      },
      component: (
        <DatePickerWithSelect
          disabledDate={current => {
            let billDate = dayjs(detailData.orderDetail.startDate)
            if (detailData.billManageList && detailData.billManageList.length > 0) {
              billDate = dayjs(detailData.billManageList[0].billDate)
            }
            return current && current <= billDate.endOf('day')
          }}
          disabledSelect={value => {
            const selectedDate = form.getFieldValue('endTime')?.datePicker
            let billDate = dayjs(detailData.orderDetail.startDate)
            if (detailData.billManageList && detailData.billManageList.length > 0) {
              billDate = dayjs(detailData.billManageList[0].billDate)
            }
            const isNextDay = selectedDate?.isSame(billDate.add(1, 'day'), 'day')
            if (isNextDay && value === PCS_COMPANION_PERIOD_ENUM.BEFORE12) {
              return true
            }
            return false
          }}
        />
      ),
    },
  ]
  const onOk = async () => {
    const { endTime } = await form.validateFields()
    const { datePicker, select } = endTime
    const params = { id: detailData.id, finishDate: formatDate(datePicker), finishDatePeriod: select }
    await requestWithTry(stopServiceApi, params)
  }

  return (
    <AekModal title='终止服务' onOk={onOk} width={420}>
      <div className='text-16px mb10px'>确认终止服务？</div>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

StopModal.PromiseThen = PromiseThen

export default StopModal
